package com.example.demo.controller;

import com.example.demo.pojo.Product;
import com.example.demo.pojo.Sale;
import com.example.demo.service.ProductService;
import com.example.demo.service.SaleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class InvoicingController {
    @Autowired
    ProductService productService;
    @Autowired
    SaleService saleService;
    @RequestMapping("toshow")
    private String toshow(){
        return "index";
    }
    @RequestMapping("getallproducts")
    @ResponseBody
    private Object getallproducts(){
        return productService.getAllProduct();
    }
    @RequestMapping("searchproduct")
    @ResponseBody
    private Product searchproduct(Product product){
        return productService.getProductByContent(product);
    }
    @RequestMapping("changeproduct")
    @ResponseBody
    private String changeproduct(Product product){
        return productService.changeProductByContent(product)>0?"ok":"no";
    }
    @RequestMapping("addsale")
    @ResponseBody
    private String addsale(Sale sale){
            int num=0;
            sale.setTotalprice(sale.getPrice()*sale.getQuantity());
            int id=sale.getProductid();
            Product product=new Product();
            product.setId(id);
            product=productService.getProductByContent(product);
            System.out.println(product);
            int count=product.getQuantity()-sale.getQuantity();
            product.setQuantity(count);
            if (count<0){
                return "no";
            }
            else {
                num=saleService.addSale(sale);
                if (num>0){
                    productService.changeProductByContent(product);
                }
            }
        return num>0?"ok":"no";
    }
    @RequestMapping("getallsales")
    @ResponseBody
    private Object getallsales(@RequestParam(defaultValue = "1") int pageNo,@RequestParam(defaultValue = "5") int pageSize,@RequestParam(defaultValue = "id")String orderBy){
        PageHelper.offsetPage((pageNo-1)* pageSize, pageSize);
        PageHelper.startPage(pageNo,pageSize,orderBy+" desc");
        List<Sale> saleList=saleService.getAllSale();
        PageInfo<Sale> pageInfo= new PageInfo<>(saleList);
        return pageInfo;
    }
}
